package vno.fux.map
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	import vno.fux.BasePoint;
	import vno.fux.events.MapEvent;
	import vno.fux.mediator.LayerMediator;
	import vno.fux.GlobalEventScheduler;
	import vno.fux.GlobalVar;
	import vno.fux.res.pool.ConfigPool;

	import vno.sci.mapEditor.Drawer;
	import flash.events.MouseEvent;

	public class MapLayer extends Sprite
	{
		private var _mapM:MapModel;
		private var _mapV:MapView;
		private var _mapC:MapController;
		private var _settings:XML;

		public function MapLayer(layerSetting_:XML)
		{
			_settings = layerSetting_;
		}
		public function create(id_:uint):void
		{
			var mapInfo:XMLList = _settings.map.(@id == id_);
			//var grid:MapGrid = initGrid(_settings.map.(@id == id_).grid[0]);
			_mapM = new MapModel({
				id			:mapInfo.@id, 
				resourceId	:mapInfo.@resId, 
				width		:mapInfo.@width, 
				height		:mapInfo.@height, 
				speed		:mapInfo.@moveSpeed,
				tileWidth	:mapInfo.tiles.@width, 
				tileHeight	:mapInfo.tiles.@height, 
				tileNumX	:mapInfo.tiles.@numX,
				tileNumY	:mapInfo.tiles.@numY,
				gridNumX	:mapInfo.grid.@col,
				gridNumY	:mapInfo.grid.@row,
				gridCellSize:mapInfo.grid.@cellSize,
				gridMatrix	:Drawer.toArray(ConfigPool.getInstance().getBinaryData("m11waypoint"))
			});
			_mapC = new MapController(_mapM);
			_mapV = new MapView(_mapM, _mapC);

			_mapC.addEventListener(MapEvent.MOVE, mapEventHandler);
			_mapC.addEventListener(MapEvent.DIRECTION, mapEventHandler);
			_mapC.addEventListener(MapEvent.START_MOVE, mapEventHandler);
			_mapC.addEventListener(MapEvent.END_MOVE, mapEventHandler);
			_mapC.addEventListener(MapEvent.UNREACH, mapEventHandler);

			GlobalEventScheduler.getInstance().addResizeListener(resizeHandler);
			
			//_mapV.addGrid(grid.gridView);
			addChild(_mapV);
		}
		public function handleMoveNeed(event:MapEvent):void
		{
			//trace("handleneed");
			//trace(event.target);
			_mapV.stimulateClick(event);
		}
		public function mapEventHandler(mevt:MapEvent):void
		{
			dispatchEvent(mevt);
		}
		public function setCoordinate(coor_:BasePoint):void
		{
			_mapC.setCoor(coor_);
		}
		public function resizeHandler(event:Event):void
		{
			this.x = GlobalVar.stage.stageWidth/2;
			this.y = GlobalVar.stage.stageHeight/2;
		}
//		private function initGrid(config:XML):MapGrid
//		{
//			var mapGrid:MapGrid = new MapGrid(config.@row, config.@col, config.@cellSize);
//			for each (var item:XML in config.item)
//			{
//				var covConf:Array = item.cover.split(',');
//				mapGrid.setPoint2(int(covConf[0]),int(covConf[1]),int(covConf[2]),int(covConf[3]),1);
//			}
//			return mapGrid;
//		}
		
		public function getPos():BasePoint
		{
			// TODO Auto Generated method stub
			return _mapM.oPoint;
		}
	}
}